package com.dongjiantong.app.controller.farmrecords.retailRecords;

import com.alibaba.dubbo.config.annotation.Reference;
import com.dongjiantong.common.exceptions.HttpCode;
import com.dongjiantong.common.exceptions.OPServerException;
import com.dongjiantong.common.model.Response;
import com.dongjiantong.common.web.sso.LoginInfo;
import com.dongjiantong.common.web.util.UserUtil;
import com.dongjiantong.farmrecords.dto.RetailRecordsImmunizationDto;
import com.dongjiantong.farmrecords.enums.FarmRecordsNumberStatus;
import com.dongjiantong.farmrecords.model.FarmRecordsRetailImmunization;
import com.dongjiantong.farmrecords.model.FarmRecordsRetailImmunizationSub;
import com.dongjiantong.farmrecords.service.FarmRecordsRetailImmunizationService;
import com.dongjiantong.farmrecords.service.FarmRecordsRetailImmunizationSubService;
import com.dongjiantong.openplatform.annotations.OpenBean;
import com.dongjiantong.openplatform.annotations.OpenMethod;
import com.github.pagehelper.PageInfo;
import com.google.common.base.Strings;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 散户养殖档案-免疫记录
 * @author Lee
 * @date 2018/1/8
 */
@Slf4j
@OpenBean
public class FarmRecordsRetailImmunizationController {
    @Reference(version = "1.0.0")
    private FarmRecordsRetailImmunizationService farmRecordsRetailImmunizationService;
    @Reference(version = "1.0.0")
    private FarmRecordsRetailImmunizationSubService farmRecordsRetailImmunizationSubService;

    /**
     * 根据养殖场id,起止时间或者状态查询免疫记录 (条件都可以为空,表示查询所有)(包含对应免疫子表中的数据)
     * @param farmId  请求的养殖场id
     * @param fromDate 请求的查询开始时间
     * @param toDate   请求的查询结束时间
     * @param pageNum
     * @param pageSize
     * @param breedSecondType 动物类型
     * @return  Response<PageInfo<FarmRecordsDisinfect>>
     */
    @OpenMethod(key = "app.farmrecords.retail.farmRecordsRetailImmunization.selectByFarmIdAndDate",
            paramNames = {"farmId","fromDate","toDate","pageNum","pageSize","breedSecondType"},
            httpMethods = RequestMethod.GET)
    public Response<PageInfo<FarmRecordsRetailImmunization>> selectByFarmIdAndDate(
            @RequestParam(required = false) Long farmId,
            @RequestParam(required = false) String fromDate,
            @RequestParam(required = false) String toDate,
            @RequestParam(required = false) Integer pageNum,
            @RequestParam(required = false) Integer pageSize,
            @RequestParam(required = false) Integer breedSecondType){

        if (farmRecordsRetailImmunizationService == null){ throw new OPServerException("请检查 farmRecordsRetailImmunizationService 服务"); }

        Map map = Maps.newHashMap();
        Long userId = UserUtil.getUserId();
        map.put("userId",userId);

        if (pageNum == null) { pageNum = 1; }
        if (pageSize == null) { pageSize = 20; }

        if (farmId != null){
            //如果养殖场id不为空,则根据养殖场id查询
            map.put("farm_id",farmId);
        }

        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            if (!Strings.isNullOrEmpty(fromDate)){
                Date startDate = sdf.parse(fromDate);
                map.put("startDate",startDate);
            }
            if (!Strings.isNullOrEmpty(toDate)){
                Date endDate = sdf.parse(toDate);
                map.put("endDate",endDate);
            }
        } catch (Exception e){
            log.error(e.getMessage());
        }

        map.put("status", FarmRecordsNumberStatus.SUBMIT.getCode());
        if (breedSecondType != null){ map.put("breed_second_type",breedSecondType); }

        PageInfo<FarmRecordsRetailImmunization> farmRecordsRetailImmunizationPageInfo = farmRecordsRetailImmunizationService.selectByMap(pageNum,pageSize,map);
        return Response.ok(farmRecordsRetailImmunizationPageInfo);
    }

    /**
     * 养殖端
     * 根据提交状态分页查询列表
     * @param farmId
     * @param status
     * @return
     */
    @OpenMethod(key = "app.farmrecords.retail.farmRecordsRetailImmunization.selectListByStatus",
            paramNames = {"farmId","status","pageSize","pageNum"},
            httpMethods = RequestMethod.GET)
    public Response<PageInfo<FarmRecordsRetailImmunization>> selectListByStatus(@RequestParam(required = false) Long farmId,
                                                                          @RequestParam(required = false) Integer status,
                                                                          @RequestParam(required = false) Integer pageSize,
                                                                          @RequestParam(required = false) Integer pageNum){
        if (farmRecordsRetailImmunizationService == null){ throw new OPServerException("farmRecordsRetailImmunizationService 服务为空,请重启服务后重试"); }
        if (farmId == null){ throw new OPServerException("养殖场id不能为空,请检查后重试"); }

        if (pageSize == null){ pageSize = 20; }
        if (pageNum == null){ pageNum = 1; }

        PageInfo<FarmRecordsRetailImmunization> farmRecordsRetailImmunizationPageInfo = farmRecordsRetailImmunizationService.selectListByStatus(pageNum,pageSize,status,farmId);

        return Response.ok(farmRecordsRetailImmunizationPageInfo);
    }

    /**
     * 根据免疫主表 主键id查询对应免疫记录
     * @param id
     * @return
     */
    @OpenMethod(key = "app.farmrecords.retail.farmRecordsRetailImmunization.selectById",
            paramNames = {"id"},
            httpMethods = RequestMethod.GET)
    public Response<RetailRecordsImmunizationDto> selectById(@RequestParam(required = false)Long id){
        if (id == null) { throw new OPServerException(HttpCode.BAD_REQUEST, "请求的id不能为空"); }
        if (farmRecordsRetailImmunizationService == null){ throw new OPServerException("farmRecordsRetailImmunizationService 为null,请检查"); }

        RetailRecordsImmunizationDto retailRecordsImmunizationDto = farmRecordsRetailImmunizationService.selectById(id);
        if (retailRecordsImmunizationDto == null){ return Response.fail(HttpCode.INTERNAL_SERVER_ERROR,"查无数据"); }

        return Response.ok(retailRecordsImmunizationDto);
    }

    /**
     * 根据免疫子表id 查询一条免疫记录信息(即 首免或者二免,三免之类)
     * @param id
     * @return
     */
    @OpenMethod(key = "app.farmrecords.retail.farmRecordsRetailImmunization.selectBySubId",
            paramNames = {"id"},
            httpMethods = RequestMethod.GET)
    public Response<FarmRecordsRetailImmunizationSub> selectBySubId(@RequestParam(required = false) Long id){
        if (id == null){ throw new OPServerException(HttpCode.BAD_REQUEST,"请求参数id不能为空"); }
        if (farmRecordsRetailImmunizationSubService == null){ throw new OPServerException("farmRecordsRetailImmunizationSubService 为null,请检查"); }

        FarmRecordsRetailImmunizationSub farmRecordsRetailImmunizationSub = farmRecordsRetailImmunizationSubService.selectBySubId(id);
        if (farmRecordsRetailImmunizationSub == null){ return Response.fail(HttpCode.INTERNAL_SERVER_ERROR,"查无数据"); }

        return Response.ok(farmRecordsRetailImmunizationSub);
    }


    /**
     * 新增一条免疫记录
     * @param retailRecordsImmunizationDto
     * @param toStatus
     * @return long 返回插入免疫记录的id
     */
    @OpenMethod(key = "app.farmrecords.retail.farmRecordsRetailImmunization.createOne",
            paramNames = {"retailRecordsImmunizationDto","toStatus"},
            httpMethods = RequestMethod.POST)
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = {Exception.class, RuntimeException.class})
    public Response<Map<String,Object>> createOne(@RequestBody(required = false)RetailRecordsImmunizationDto retailRecordsImmunizationDto,
                                                  @RequestParam(required = false) Integer toStatus){
        if (retailRecordsImmunizationDto == null) { throw new OPServerException(HttpCode.BAD_REQUEST, "请求参数对象不能为空"); }
        if (farmRecordsRetailImmunizationService == null){ throw new OPServerException("farmRecordsRetailImmunizationService 为null,请检查"); }

        LoginInfo loginInfo = UserUtil.getCurrentUser();

        Map<String,Object> result = farmRecordsRetailImmunizationService.createOne(loginInfo,retailRecordsImmunizationDto, toStatus);

        return Response.ok(result);
    }

    /**
     * 正常更新免疫记录(免疫主表 免疫子表)
     * @param retailRecordsImmunizationDto 请求的对象
     * @param toStatus
     * @return  boolean (更新成功返回true 反之返回false)
     */
    @OpenMethod(key = "app.farmrecords.retail.farmRecordsRetailImmunization.updateByIdOrNumber",
            paramNames = {"farmRecordsImmunization","vaccines","toStatus","original_ear_list"},
            httpMethods = RequestMethod.POST)
    public Response<Map<String,Object>> updateByIdOrNumber(@RequestBody (required = false) RetailRecordsImmunizationDto retailRecordsImmunizationDto,
                                                           @RequestParam(required = false) Integer toStatus){
        if (farmRecordsRetailImmunizationService == null){ throw new OPServerException("farmRecordsRetailImmunizationService 为null,请检查"); }
        if (retailRecordsImmunizationDto == null) { throw new OPServerException(HttpCode.BAD_REQUEST,HttpCode.BAD_REQUEST.getMessage()); }

        LoginInfo loginInfo = UserUtil.getCurrentUser();

        Integer con = farmRecordsRetailImmunizationService.updateByIdOrNumber(loginInfo,retailRecordsImmunizationDto,toStatus);

        Map<String,Object> map = Maps.newHashMap();
        if (con == 1) {
            map.put("updateResult","true");
        }else {
            map.put("updateResult","false");
        }

        return Response.ok(map);
    }

    /**
     * 更新免疫单据耳标号
     * 更新免疫记录(只更新免疫记录主表 耳标)
     */
    @OpenMethod(key = "app.farmrecords.retail.farmRecordsRetailImmunization.updateEarNumber",
            paramNames = {"farmRecordsImmunization","farmRecordsImmunizationSubList","original_ear_list"},
            httpMethods = RequestMethod.GET)
    public Response<Map<String,Object>> updateEarNumber(RetailRecordsImmunizationDto retailRecordsImmunizationDto){
        Map<String,Object> map = Maps.newHashMap();
        Boolean result = false;

        LoginInfo loginInfo = UserUtil.getCurrentUser();

        FarmRecordsRetailImmunization farmRecordsRetailImmunization = retailRecordsImmunizationDto.getImmunizationRecord();
        List<FarmRecordsRetailImmunizationSub> farmRecordsRetailImmunizationSubList = retailRecordsImmunizationDto.getVaccines();
        List<String> original_ear_list = retailRecordsImmunizationDto.getOriginal_ear();

        if (farmRecordsRetailImmunizationSubList.size() == 0) {
            result = farmRecordsRetailImmunizationService.updateEarNumber(loginInfo,farmRecordsRetailImmunization,original_ear_list);
        }

        map.put("result",result);
        return Response.ok(map);
    }
}
